/////////////////////////////////////////////////////////////////////
// DBMessageHandler.cpp
//
//
// 11/16/2010
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "DBMessageHandler.h"
#include "Message/DBMessage.h"
#include "DBMessageHandlerMapper.h"

using namespace woe;

extern INT64	sqlResult = 0;
DBMessageHandler::MessageMap DBMessageHandler::ms_MessageMap;
Service* DBMessageHandler::m_wpSvcLgc = NULL;
DBMysql DBMessageHandler::m_DBMysql;

DBMessageHandler::DBMessageHandler(  )
{
	
}

DBMessageHandler::~DBMessageHandler(  )
{
}

bool DBMessageHandler::initialize(IMsgHandlerInitData* data)
{
	MsgHandlerInitDataDB* d = dynamic_cast<MsgHandlerInitDataDB*>(data);
	if (d)
	{
		m_wpSvcLgc = d->wpSvcLgc;

		DBMessageHandlerMapper mapper(this);

		if (m_DBMysql.Create( d->db_server, d->db_user, d->db_password, d->db_name, d->db_port))
		{
			LOG_INFO("Success to connect to database!");
			return true;
		}
		else
		{
			LOG_INFO("Failed to connect to database!");
			return false;
		}
		return true;
	}
	else
		return false;
}


void DBMessageHandler::addSubHandler( int nMsgCate, int nMsgID, IMsgHandler* pHandler )
{
	ms_MessageMap.insert( MessageMap::value_type( int((nMsgCate<<16) | nMsgID), pHandler ) );
}

void DBMessageHandler::rmvSubHandler( int nMsgCate, int nMsgID)
{;
}


bool DBMessageHandler::handleMsg( IMsg * message )
{
	int nKey = (int)message->getMsgCate();
	nKey <<= 16;
	nKey |= message->getMsgID();

	MessageMapConstIter iter = ms_MessageMap.find( nKey );
	if ( iter != ms_MessageMap.end() )
	{
		iter->second->handleMsg( message );
	}
	else
	{
		// log()
		return false;
	}
	return true;
}